// 二次封装uni.showToast()
export const Toast = (title: string) => {
  return new Promise(reslove => {
    // uni.showToast 在真机上超过一定长度会被省略，使用 uni.showModal 来显示长文本
    // 根据实际测试，大约 7-8 个字符后会省略，这里设置为 10 个字符为分界线
    const showAsModal = title.length > 10;

    if (showAsModal) {
      uni.showModal({
        title: '',
        content: title,
        showCancel: false,
        confirmText: '确定',
        success: () => {
          reslove(undefined);
        },
      });
    } else {
      uni.showToast({
        title,
        icon: 'none',
      });
      let time = setTimeout(() => {
        clearTimeout(time);
        reslove(time);
      }, 3000);
    }
  });
};

// 页面传递多个参数处理
export const stringifyParams = (params: Record<string, any>) => {
  return encodeURIComponent(JSON.stringify(params));
};

// 页面接收多个参数处理
export const parseParams = (params: string = '{}') => {
  return JSON.parse(decodeURIComponent(params));
};

// 正则表达式
export const regRules = {
  phone: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57]|199)[0-9]{8}$/, // 手机号码正则
};

// 判断地址位置是否授权，否则弹出设置
export const getWXUserLocation = (): Promise<UniApp.GetLocationSuccess> => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success(res) {
        console.log(res.authSetting);
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          uni.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (r) {
              if (r.cancel) {
                uni.showToast({ title: '拒绝授权' });
              } else if (r.confirm) {
                uni.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting['scope.userLocation'] == true) {
                      uni.showToast({ title: '授权成功' });
                      //再次授权，调用wx.getLocation的API
                      getLocation().then(glRes => resolve(glRes));
                    } else {
                      uni.showToast({ title: '授权失败' });
                    }
                  },
                });
              }
            },
          });
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          getLocation().then(glRes => resolve(glRes));
        } else {
          //调用wx.getLocation的API
          getLocation().then(glRes => resolve(glRes));
        }
      },
      fail(err) {
        reject(err);
      },
    });
  });
};

export const getLocation = (): Promise<UniApp.GetLocationSuccess> => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      geocode: true,
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
        console.log(err);
      },
    });
  });
};

// 计算两个经纬度之间的距离
type unitEnum = 'km' | 'm' | 'miles';
export function calculateDistance(lat1: number, lon1: number, lat2: number, lon2: number, unit: unitEnum = 'km') {
  const rMap: Record<unitEnum, number> = {
    km: 6371,
    m: 6371000,
    miles: 3958.8,
  };
  const R = rMap[unit];

  const lat1Rad = (lat1 * Math.PI) / 180;
  const lat2Rad = (lat2 * Math.PI) / 180;
  const lon1Rad = (lon1 * Math.PI) / 180;
  const lon2Rad = (lon2 * Math.PI) / 180;

  const latDiff = lat2Rad - lat1Rad;
  const lonDiff = lon2Rad - lon1Rad;

  const a =
    Math.sin(latDiff / 2) * Math.sin(latDiff / 2) +
    Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lonDiff / 2) * Math.sin(lonDiff / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  const distance = R * c;

  return distance;
}

// 登录状态管理
let isNavigatingToLogin = false; // 防止重复跳转登录页

export const checkLoginAndNavigate = () => {
  const auth = uni.getStorageSync('token');
  if (!auth && !isNavigatingToLogin) {
    isNavigatingToLogin = true;
    uni.navigateTo({
      url: '/pages/login/index',
      success: () => {
        // 跳转成功后重置标志
        setTimeout(() => {
          isNavigatingToLogin = false;
        }, 1000);
      },
      fail: () => {
        // 跳转失败也重置标志
        isNavigatingToLogin = false;
      },
    });
    return false;
  }
  return !!auth;
};

// 从URL中提取文件名
function getFilenameFromUrl(url: string) {
  try {
    const urlObj = new URL(url);
    const pathname = urlObj.pathname;
    return pathname.substring(pathname.lastIndexOf('/') + 1) || 'image';
  } catch (e) {
    return 'image';
  }
}

/**
 * h5下载图片
 */
export const downLoadImage = (url: string, filename?: string) => {
  // 从URL中提取文件名
  const _filename = getFilenameFromUrl(url);
  const finalFilename = filename || _filename || '壁纸';

  // 创建图片对象获取图片数据
  const img = new Image();
  img.crossOrigin = 'Anonymous'; // 解决跨域问题
  img.onload = function () {
    // 创建canvas
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;

    // 将图片绘制到canvas上
    const ctx = canvas.getContext('2d');
    ctx?.drawImage(img, 0, 0);

    // 将canvas转换为blob
    canvas.toBlob(function (blob) {
      if (blob) {
        // 创建下载链接
        const a = document.createElement('a');
        a.style.display = 'none';

        // 创建临时URL
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = finalFilename;

        // 触发下载
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);

        // 释放URL对象
        window.URL.revokeObjectURL(url);
      } else {
        uni.showToast({
          title: '图片下载失败',
          icon: 'error',
        });
      }
    });
  };

  img.onerror = function () {
    uni.showToast({
      title: '图片加载失败',
      icon: 'error',
    });
  };

  // 开始加载图片
  img.src = url;
};
